package com.xmb.wcapi.aspect;

import com.xmb.wcapi.constant.LayTableR;
import com.xmb.wcapi.constant.R;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class ValidateJWTAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    @Pointcut("@annotation(com.xmb.wcapi.annotation.ValidateJWT)")
    public void pointcut() { }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) {
        // 请求开始时间
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = null;
        if (sra != null) {
            token = sra.getRequest().getHeader("apiToken");
        }
        //校验token
        if (token != null && !token.isEmpty()) {
            Boolean hasKey = redisTemplate.hasKey("api:" + token);
            if (Boolean.TRUE.equals(hasKey)){
                try {
                    return point.proceed();
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
            return LayTableR.result(500,0,"请登录！");
        }
        return LayTableR.result(500,0,"请在Header中携带apiToken");
    }

}
